import datetime
import time

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.http import QueryDict, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import TemplateView, CreateView, ListView, DetailView
from el_pagination.views import AjaxListView

from malfunctions.models import Incident
from malfunctions.send_email import fault_send_mail
from .forms import MalfunctionCreateForm, MalfunctionHandleForm
from accounts.models import CustomUser


class MalfunctionCreateView(CreateView):
    """ 添加故障 """
    success_url = reverse_lazy('malfunction_list')
    template_name = 'malfunction/malfunction_create.html'
    form_class = MalfunctionCreateForm

    def get_context_data(self, **kwargs):
        date_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        kwargs.update({'date_time': date_time})
        return super().get_context_data(**kwargs)

    def form_valid(self, form):

        form.cleaned_data['incident_user'] = self.request.user.username

        form_ = form.cleaned_data

        close_user = self.request.POST.get("status", False)  # 0:处理中  1:未处理故障  2:关闭
        status_display = form.instance.get_status_display()  # 0:处理中  1:未处理故障  2:关闭 转换为文字
        if not close_user:
            return super().form_valid(form)

        project_principal = form.cleaned_data.get("project_principal", None)
        if project_principal:
            # 获取项目负责人邮箱
            user_obj = CustomUser.objects.filter(Q(username=project_principal) | Q(email=project_principal))
            if user_obj.exists():
                user_obj = user_obj.first()
                project_principal = user_obj.email

        # 发送邮件  todo 分离
        fault_send_mail(
            incident_user=form_.get("incident_user"),
            mailcomment=form_.get("mailcomment"),
            get_status_display=status_display,
            starttime=form_.get("starttime"),
            scantime=form_.get("scantime"),
            stoptime=form_.get("stoptime"),
            content=form_.get("comment"),  # 处理过程
            mail_title=form_.get("title"),
            project_principal=project_principal,
        )

        return super().form_valid(form)


class MalfunctionUnhandledView(TemplateView):
    """处理中,待处理 故障"""
    template_name = 'malfunction/malfunction_unhandled.html'



    def get_queryset(self):
        name = self.request.GET.get('search')
        queryset = Incident.objects.filter(status__lte=1).order_by("-createtime")
        if name:
            queryset = queryset.filter(title__contains=name)
        return queryset

    def get_context_data(self, **kwargs):
        incident_obj = self.get_queryset()
        #  分页
        paginator = Paginator(incident_obj, 6, 1)
        page = self.request.GET.get('page')
        try:
            pagintor_obj = paginator.page(page)
        except  PageNotAnInteger:
            pagintor_obj = paginator.page(1)
        except EmptyPage:
            pagintor_obj = paginator.page(paginator.num_pages)
        context = {'pagintor_obj': pagintor_obj}
        kwargs.update(context)
        return super().get_context_data(**kwargs)


class MalfunctionHandleView(TemplateView):
    """ 处理故障 """
    template_name = 'malfunction/malfunction_handle.html'

    def get_context_data(self, **kwargs):
        malfunction_obj = get_object_or_404(Incident, pk=self.kwargs.get('pk'))
        malfunction_form = MalfunctionHandleForm(instance=malfunction_obj)
        kwargs.update({'malfunction_form': malfunction_form})
        kwargs.update({'malfunction_obj': malfunction_obj})
        return super().get_context_data(**kwargs)

    def post(self, request, **kwargs):
        status = QueryDict(self.request.body).get('status', False)  # 0 处理中, 1 未处理  2 关闭
        print(status, '11111')
        malfunction_obj = get_object_or_404(Incident, pk=self.kwargs.get('pk'))

        malfunction_form = MalfunctionHandleForm(request.POST, instance=malfunction_obj)
        if malfunction_form.is_valid():
            form = malfunction_form.save(commit=False)
            if int(status) == 1:
                form.closeuser = request.user.username
            if not QueryDict(self.request.body).get('stoptime', False):
                form.stoptime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            form.save()

            project_principal = form.project_principal
            if project_principal:
                # 获取项目负责人邮箱
                user_obj = CustomUser.objects.filter(Q(username=project_principal) | Q(email=project_principal))
                if user_obj.exists():
                    user_obj = user_obj.first()
                    project_principal = user_obj.email
            # todo 分离
            fault_send_mail(
                incident_user=malfunction_obj.incident_user,
                mailcomment=form.mailcomment,
                get_status_display=form.get_status_display(),
                starttime=form.starttime,
                scantime=form.scantime,
                stoptime=form.stoptime,
                content=form.comment,  # 处理过程
                mail_title=form.title,
                project_principal=project_principal,
            )
            return HttpResponseRedirect(reverse_lazy('malfunction_list'))

        context = {"malfunction_form": malfunction_form, "malfunction_obj": malfunction_obj}
        return render(request, self.template_name, context)


class MalfunctionListView(AjaxListView):
    """ 故障列表"""
    template_name = 'malfunction/malfunction_list.html'
    context_object_name = 'incident_obj'

    def get_queryset(self):
        name = self.request.GET.get('search')
        queryset = Incident.objects.all().order_by("-createtime")
        if name:
            queryset = queryset.filter(title__contains=name)
        return queryset


    def get_context_data(self, **kwargs):
        incident_obj = self.get_queryset()
        #  分页
        paginator = Paginator(incident_obj, 6, 1)
        page = self.request.GET.get('page')
        try:
            pagintor_obj = paginator.page(page)
        except  PageNotAnInteger:
            pagintor_obj = paginator.page(1)
        except EmptyPage:
            pagintor_obj = paginator.page(paginator.num_pages)
        context = {'pagintor_obj': pagintor_obj}
        kwargs.update(context)
        return super().get_context_data(**kwargs)


class MalfunctionDetailView(DetailView):
    """ 故障详情 """
    template_name = 'malfunction/malfunction_detail.html'
    model = Incident
    context_object_name = 'data'


class MalfunctionDoneView(TemplateView):
    """ 已处理故障"""
    template_name = 'malfunction/malfunction_done.html'

    def get_queryset(self):
        name = self.request.GET.get('search')
        queryset = Incident.objects.filter(status=2).order_by("-createtime")
        if name:
            queryset = queryset.filter(title__contains=name, )
        return queryset


    def get_context_data(self, **kwargs):
        incident_obj = self.get_queryset()
        #  分页
        paginator = Paginator(incident_obj, 6, 1)
        page = self.request.GET.get('page')
        try:
            pagintor_obj = paginator.page(page)
        except  PageNotAnInteger:
            pagintor_obj = paginator.page(1)
        except EmptyPage:
            pagintor_obj = paginator.page(paginator.num_pages)
        context = {'pagintor_obj': pagintor_obj}
        kwargs.update(context)
        return super().get_context_data(**kwargs)


class MalfunctionMyView(TemplateView):
    """我的故障 """
    template_name = 'malfunction/malfunction_my.html'

    def get_queryset(self):
        name = self.request.GET.get('search')
        queryset = Incident.objects.filter(
            projectuser=self.request.user.username, status__gte=1).order_by("-createtime")
        if name:
            queryset = queryset.filter(title__contains=name, )

        return queryset

    def get_context_data(self, **kwargs):
        incident_obj = self.get_queryset()
        #  分页
        paginator = Paginator(incident_obj, 6, 1)
        page = self.request.GET.get('page')
        try:
            pagintor_obj = paginator.page(page)
        except  PageNotAnInteger:
            pagintor_obj = paginator.page(1)
        except EmptyPage:
            pagintor_obj = paginator.page(paginator.num_pages)
        context = {'pagintor_obj': pagintor_obj}
        kwargs.update(context)
        return super().get_context_data(**kwargs)


class FaultClassicalView(TemplateView):
    """经典故障"""
    template_name = 'malfunction/malfunction_classical.html'

    def get_queryset(self):
        name = self.request.GET.get('search')
        queryset = Incident.objects.filter(classical=True).order_by("-createtime")
        if name:
            queryset = queryset.filter(title__contains=name, )
        return queryset


    def get_context_data(self, **kwargs):
        incident_obj = self.get_queryset()
        #  分页
        paginator = Paginator(incident_obj, 6, 1)
        page = self.request.GET.get('page')
        try:
            pagintor_obj = paginator.page(page)
        except  PageNotAnInteger:
            pagintor_obj = paginator.page(1)
        except EmptyPage:
            pagintor_obj = paginator.page(paginator.num_pages)
        context = {'pagintor_obj': pagintor_obj}
        kwargs.update(context)
        return super().get_context_data(**kwargs)
